// ScreenCaptureService.java
package com.poker.monitor.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.content.pm.ServiceInfo;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.Image;
import android.media.ImageReader;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.IBinder;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;

import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;

import com.poker.monitor.model.GameState;
import com.poker.monitor.model.Player;
import com.poker.monitor.ocr.OcrCallback;
import com.poker.monitor.ocr.OcrException;
import com.poker.monitor.ocr.OcrService;
import com.poker.monitor.recognition.RegionRecognizer;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

public class ScreenCaptureService extends Service {
    // 截图相关静态变量
    public static int resultCode;
    public static Intent resultData;
    private static boolean mImageAvailable = false;

    // 原有成员变量
    private static final String VIRTUAL_DISPLAY_NAME = "poker_capture";
    private MediaProjection mediaProjection;
    private VirtualDisplay virtualDisplay;
    private ImageReader imageReader;
    private int screenWidth;
    private int screenHeight;
    private int screenDensity;
    private OcrService ocrService;
    private GameState gameState;
    private static final int NOTIFICATION_ID = 1;
    private static final String CHANNEL_ID = "screen_capture_channel";
    private RegionRecognizer regionRecognizer;

    @Override
    public void onCreate() {
        super.onCreate();
        startMediaProjectionForeground();
        initScreenParameters();
        initMediaProjection();
        setupVirtualDisplay();
        initServices();
    }

    private void startMediaProjectionForeground() {
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        createNotificationChannel(notificationManager);

        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("屏幕监控服务运行中")
                .setContentText("正在捕获屏幕内容")
                .setSmallIcon(android.R.drawable.ic_menu_camera)
                .build();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION);
        } else {
            startForeground(NOTIFICATION_ID, notification);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void createNotificationChannel(NotificationManager notificationManager) {
        NotificationChannel channel = new NotificationChannel(
                CHANNEL_ID,
                "屏幕录制",
                NotificationManager.IMPORTANCE_DEFAULT
        );
        notificationManager.createNotificationChannel(channel);
    }

    private void initScreenParameters() {
        WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        DisplayMetrics metrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getRealMetrics(metrics);
        screenWidth = metrics.widthPixels;
        screenHeight = metrics.heightPixels;
        screenDensity = metrics.densityDpi;
    }

    private void initMediaProjection() {
        MediaProjectionManager mediaProjectionManager =
                (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
        mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, resultData);
    }

    private void setupVirtualDisplay() {
        mediaProjection.registerCallback(new MediaProjection.Callback() {
            @Override
            public void onStop() {
                super.onStop();
                stopCapture();
            }
        }, null);

        imageReader = ImageReader.newInstance(screenWidth, screenHeight, PixelFormat.RGBA_8888, 2);
        imageReader.setOnImageAvailableListener(reader -> {
            Bitmap bitmap = processImageReader(reader);
            if (bitmap != null) {
//                saveScreenshot(bitmap);    // 新增截图保存
                processScreenshot(bitmap); // 原有处理逻辑
            }
        }, null);

        virtualDisplay = mediaProjection.createVirtualDisplay(
                VIRTUAL_DISPLAY_NAME,
                screenWidth,
                screenHeight,
                screenDensity,
                DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
                imageReader.getSurface(),
                null,
                null
        );
    }

    private Bitmap processImageReader(ImageReader reader) {
        try (Image image = reader.acquireLatestImage()) {
            if (image == null) return null;

            Image.Plane plane = image.getPlanes()[0];
            ByteBuffer buffer = plane.getBuffer();
            int pixelStride = plane.getPixelStride();
            int rowStride = plane.getRowStride();
            int rowPadding = rowStride - pixelStride * image.getWidth();

            Bitmap bitmap = Bitmap.createBitmap(
                    image.getWidth() + rowPadding / pixelStride,
                    image.getHeight(),
                    Bitmap.Config.ARGB_8888);
            bitmap.copyPixelsFromBuffer(buffer);

            return Bitmap.createBitmap(bitmap, 0, 0, image.getWidth(), image.getHeight());
        } catch (Exception e) {
            Log.e("ScreenCapture", "图像处理错误", e);
            return null;
        }
    }

    private void saveScreenshot(Bitmap bitmap) {
        try {
            File outputDir = getExternalFilesDir(null);
            String fileName = String.format(Locale.CHINA,
                    "SCR-%1$tY%1$tm%1$td-%1$tH%1$tM%1$tS.png",
                    Calendar.getInstance());

            FileOutputStream fos = new FileOutputStream(new File(outputDir, fileName));
            bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
            fos.close();

            Log.d("ScreenCapture", "截图保存: " + fileName);
        } catch (Exception e) {
            Log.e("ScreenCapture", "保存截图失败", e);
        } finally {
//            if (bitmap != null && !bitmap.isRecycled()) {
//                bitmap.recycle();
//            }
        }
    }

    // 以下是原有保持不变的功能代码
    private void initServices() {
        ocrService = new OcrService();
        gameState = new GameState();
    }

    private void processScreenshot(Bitmap bitmap) {
        if (regionRecognizer == null) {
            regionRecognizer = new RegionRecognizer();
            regionRecognizer.updateRegions(screenWidth, screenHeight);
        }

        List<Bitmap> playerBitmaps = regionRecognizer.extractPlayerRegions(bitmap);
        for (int i = 0; i < playerBitmaps.size(); i++) {
            processPlayerBitmap(playerBitmaps.get(i), i + 1);
        }

        bitmap.recycle();
    }

    private void processPlayerBitmap(Bitmap bitmap, int playerIndex) {
        try {
            ocrService.recognizeText(bitmap, new OcrCallback() {
                @Override
                public void onSuccess(JSONArray results) {
                    StringBuilder playerInfo = new StringBuilder();
                    try {
                        for (int i = 0; i < results.length(); i++) {
                            JSONObject result = results.getJSONObject(i);
                            if (result.getDouble("score") > 0.5) {
                                playerInfo.append(result.getString("text")).append(" ");
                            }
                        }

                        if (playerInfo.length() > 0) {
                            List<Player> players = gameState.getPlayers();
                            Player player = players.get(playerIndex - 1);
                            player.setName(playerInfo.toString().trim());
                            player.setActive(true);
//                            gameState.updatePlayers(players);
                        }
                    } catch (JSONException e) {
                        Log.e("ScreenCapture", "OCR结果解析异常", e);
                    }
                }

                @Override
                public void onFailure(OcrException exception) {
                    Log.e("ScreenCapture", "OCR识别失败[" + exception.getErrorType() + "]: " + exception.getMessage());
                }
            });

            if (!bitmap.isRecycled()) {
                bitmap.recycle();
            }
        } catch (Exception e) {
            Log.e("ScreenCapture", "OCR处理错误", e);
        }
    }


    private void stopCapture() {
        if (virtualDisplay != null) {
            virtualDisplay.release();
            virtualDisplay = null;
        }
        if (mediaProjection != null) {
            mediaProjection.stop();
            mediaProjection = null;
        }
    }

    @Override
    public void onDestroy() {
        stopCapture();
        super.onDestroy();
    }

    // 原有Binder实现保持不变
    private final IBinder binder = new LocalBinder();

    public class LocalBinder extends android.os.Binder {
        public ScreenCaptureService getService() {
            return ScreenCaptureService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }
}
